package com.haierCamera.customapplication.ui.plan;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import dagger.Lazy;

import com.haierCamera.customapplication.BaseActivity;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.ApiService;
import com.haierCamera.customapplication.ui.business.Business;
import com.haierCamera.customapplication.ui.business.entity.ChannelInfo;
import com.haierCamera.customapplication.ui.custom.BaseListenerOnClik;
import com.haierCamera.customapplication.utils.ResourceConvertUtils;
import com.haierCamera.customapplication.utils.android.HttpErrorProcess;
import com.haierCamera.customapplication.utils.testdate.adapter.NumericWheelAdapter;
import com.haierCamera.customapplication.utils.testdate.widget.WheelView;
import com.lechange.opensdk.api.bean.DeviceAlarmPlan;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

/**
 * Created by AdministratorZJ
 * on 2018/6/21.
 */

public class HZKLPlanTimeSettingActivity extends BaseActivity {
    private LinearLayout startRe, endRe, button, settingPeriod;
    private TextView startTime, endTime, periodTv;
    private List<DeviceAlarmPlan.ResponseData.RulesElement> rules = new ArrayList<>();
    private ChannelInfo channelInfo;
    private String deviceCode;
    private ProgressDialog progressDialog;

    @Inject
    Lazy<HttpErrorProcess> httpErrorProcessLazy;
    @Inject
    ApiService apiService;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hzkl_activity_plan_time_setting);
        startRe = (LinearLayout) findViewById(R.id.setting_start);
        startTime = (TextView) findViewById(R.id.setting_start_time);
        endRe = (LinearLayout) findViewById(R.id.setting_end);
        endTime = (TextView) findViewById(R.id.setting_end_time);
        periodTv = (TextView) findViewById(R.id.setting_period_time);
        button = (LinearLayout) findViewById(R.id.setting_sure);
        settingPeriod = (LinearLayout) findViewById(R.id.setting_period);
        initTitle();
        initData();
    }

    /**
     * 初始化标题栏
     */
    public void initTitle() {
        // 绘制标题
        Toolbar toolbar=findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    private void initData() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("加载中...");
        deviceCode = getIntent().getStringExtra("deviceCode");
//        channelInfo = Business.getInstance().getChannel(deviceCode);
        initHourData();
        startRe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimeDialog(v.getId(), getCurHour());
            }
        });
        endRe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimeDialog(v.getId(), getCurHour());
            }
        });
        settingPeriod.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(HZKLPlanTimeSettingActivity.this, HZKLPeriodSettingActivity.class), 0);
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                settingPlan();
            }
        });
        getAlarmPlanConfig();
    }

    String week;

    @SuppressLint("HandlerLeak")
    private void getAlarmPlanConfig() {
        week = "";
        progressDialog.show();
        Log.i("TAG","deviceCode-" + deviceCode);
        Business.getInstance().getAlarmPlanConfig(deviceCode,"0", new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0) {
                    progressDialog.dismiss();
                    List<DeviceAlarmPlan.ResponseData.RulesElement> rulesElements = (List<DeviceAlarmPlan.ResponseData.RulesElement>) (((Business.RetObject) msg.obj).resp);
                    if (rulesElements.size() == 0) {
                        return;
                    }
                    StringBuffer sbf = new StringBuffer();
                    for (int i = 0; i < rulesElements.size(); i++) {
                        if (rulesElements.get(i).enable) {
                            sbf.append("," + rulesElements.get(i).period);
                        }
                    }
                    String period ="";
                    if (sbf.toString().length() !=0) {
                        period =  sbf.toString().substring(1,sbf.toString().length());
                    }
                    Log.i("TAG","period-" + period);
                    String beginTime = rulesElements.get(0).beginTime;
                    startTime.setText(beginTime.substring(0, 5));
                    String endTimeNum = rulesElements.get(0).endTime;
                    endTime.setText(endTimeNum.substring(0, 5));
//                    String period = rulesElements.get(0).period;
                    if ("Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".equals(period)) {
                        week = "每天";
                    } else if ("Monday,Tuesday,Wednesday,Thursday,Friday".equals(period)) {
                        week = "工作日";
                    } else {
                        if (period.contains("Monday")) {
                            week = "每周一";
                        }
                        if (period.contains("Tuesday")) {
                            week += "每周二";
                        }
                        if (period.contains("Wednesday")) {
                            week += "每周三";
                        }
                        if (period.contains("Thursday")) {
                            week += "每周四";
                        }
                        if (period.contains("Friday")) {
                            week += "每周五";
                        }
                        if (period.contains("Saturday")) {
                            week += "每周六";
                        }
                        if (period.equals("Sunday")) {
                            week += "每周日";
                        }
                    }
                    periodTv.setText(week);
                } else {
                    progressDialog.dismiss();
                    Toast.makeText(HZKLPlanTimeSettingActivity.this, ((Business.RetObject) msg.obj).mMsg, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    String setWeek;

    private void settingPlan() {
        progressDialog.show();
        DeviceAlarmPlan.ResponseData.RulesElement rulesElement = new DeviceAlarmPlan.ResponseData.RulesElement();
        rulesElement.beginTime = startTime.getText().toString().trim() + ":00";
        rulesElement.endTime = endTime.getText().toString().trim() + ":00";
        String period = null;
                                                                                                                                                        setWeek = "";
        if ("每天".equals(periodTv.getText().toString().trim())) {
            setWeek = "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday";
        } else if ("工作日".equals(periodTv.getText().toString().trim())) {
            setWeek = "Monday,Tuesday,Wednesday,Thursday,Friday";
        } else {
            if (periodTv.getText().toString().trim().contains("每周一")) {
                setWeek = "Monday";
            }
            if (periodTv.getText().toString().trim().contains("每周二")) {
                if (setWeek!=null && setWeek.length()>0) {
                    setWeek += ",Tuesday";
                } else {
                    setWeek = "Tuesday";
                }
            }
            if (periodTv.getText().toString().trim().contains("每周三")) {
                if (setWeek!=null && setWeek.length()>0) {
                    setWeek += ",Wednesday";
                } else {
                    setWeek = "Wednesday";
                }
            }
            if (periodTv.getText().toString().trim().contains("每周四")) {
                if (setWeek!=null && setWeek.length()>0) {
                    setWeek += ",Thursday";
                } else {
                    setWeek = "Thursday";
                }
            }
            if (periodTv.getText().toString().trim().contains("每周五")) {
                if (setWeek!=null && setWeek.length()>0) {
                    setWeek += ",Friday";
                } else {
                    setWeek = "Friday";
                }
            }
            if (periodTv.getText().toString().trim().contains("每周六")) {
                if (setWeek!=null && setWeek.length()>0) {
                    setWeek += ",Saturday";
                } else {
                    setWeek = "Saturday";
                }
            }
            if (periodTv.getText().toString().trim().contains("每周日")) {
                if (setWeek!=null && setWeek.length()>0) {
                    setWeek += ",Sunday";
                } else {
                    setWeek = "Sunday";
                }
            }
        }
        Log.i("TAG","setWeek-" + setWeek);
        rulesElement.period = setWeek;
        rules.clear();
        rules.add(rulesElement);

        modifyAlarmPlans(deviceCode,"0"
                ,rulesElement.period
                ,rulesElement.beginTime
                ,rulesElement.endTime);

//        Business.getInstance().setAlarmPlanConfig(deviceCode, "0", rules, new Handler() {
//            @Override
//            public void handleMessage(Message msg) {
//                super.handleMessage(msg);
//                if (msg.what == 0) {
//                    progressDialog.dismiss();
//                    Toast.makeText(HZKLPlanTimeSettingActivity.this, "设置成功", Toast.LENGTH_SHORT).show();
//                    finish();
//                } else {
//                    progressDialog.dismiss();
//                    Toast.makeText(HZKLPlanTimeSettingActivity.this, "设置失败-" + msg.what, Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
    }

    public void modifyAlarmPlans(String sn,String channel,String period,String beginTime,String endTime) {
        ResourceConvertUtils.convertToResource(apiService.modifyAlarmPlans(sn, channel, period, beginTime, endTime))
                .observe(this, resource -> {
                    assert resource != null;
                    switch (resource.status) {
                        case ERROR:
                            httpErrorProcessLazy.get().process(resource);
//                            binding.swipe.setRefreshing(false);
                            break;
                        case SUCCESS:
                            Log.i("TAG","modify-success");
                            toast("设置成功");
                            finish();
                            break;
                        case LOADING:
                            break;

                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            String period = data.getStringExtra("period");
            periodTv.setText(period);
        }
    }

    //---------------------------- 时间选择器控件  ------------------------------

    private ArrayList<String> hourList;

    private void initHourData() {
        if (hourList == null) hourList = new ArrayList<String>();
        for (int i = 0; i < 24; i++) {
            hourList.add(String.format("%02d", i) + " : 00");
        }
    }

    /**
     * 时间选择器Dialog
     *
     * @param viewId  - 点击的ViewID
     * @param curHour - 当前小时
     */
    private void showTimeDialog(final int viewId, int curHour) {
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.show();
        Window window = dialog.getWindow();
        // 设置布局
        window.setContentView(R.layout.hzkl_timepick);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        // 设置弹出的动画效果
        window.setWindowAnimations(R.style.HZKLAnimBottom);

        final WheelView hWheelView = (WheelView) window.findViewById(R.id.hour);
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, hourList);
        hWheelView.setViewAdapter(numericWheelAdapter);
        hWheelView.setCyclic(false);
        hWheelView.setCurrentItem(curHour);
        hWheelView.setVisibleItems(7);

        // 设置监听
        Button ok = (Button) window.findViewById(R.id.set);
        Button cancel = (Button) window.findViewById(R.id.cancel);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                int selectHour = hWheelView.getCurrentItem();
                switch (viewId) {
                    case R.id.setting_start:
                        startTime.setText(getMMdd(selectHour));
                        break;
                    case R.id.setting_end:
                        endTime.setText(getMMdd(selectHour));
                        break;
                    default:
                        break;
                }

                dialog.cancel();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.cancel();
            }
        });
        LinearLayout cancelLayout = (LinearLayout) window.findViewById(R.id.view_none);
        cancelLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                dialog.cancel();
                return false;
            }
        });
    }

    /**
     * 功能描述：返回小
     *
     * @return 返回小时
     */
    public static int getCurHour() {
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        return calendar.get(Calendar.HOUR_OF_DAY);
    }


    /**
     * 把分钟数转换成"MM:dd"的时间格式
     *
     * @return
     */
    private String getMMdd(int hour) {
        int min = 0;

        String time = String.format("%02d", hour) + ":" + String.format("%02d", min);
        return time;
    }
}
